package com.example.jason.helloworld;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        if (MainActivity.mSmsListenEnabled) {
            // 睡眠3秒，等待系统信息APP将短信写入数据库
            Log.i(">>>>>>>>>>", "onReceive: 新短信！");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Uri uri = Uri.parse("content://sms/inbox");
            // 获取短信中最新的未读短信
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type",};
            Cursor idCursor = context.getContentResolver().query(uri, projection, "read = ?", new String[]{"0"}, "date desc");
            assert idCursor != null;
            Log.i(">>>>>>>>>>", "onReceive: 读取短信！");
            if (idCursor.moveToFirst()) {
                int addressIdx = idCursor.getColumnIndex("address");
                int bodyIdx = idCursor.getColumnIndex("body");
                String address = idCursor.getString(addressIdx);
                String body = idCursor.getString(bodyIdx);
                Log.i(">>>>>>>>>>", "onReceive: " + address + ":" + body);
                Bundle bdl = new Bundle();
                bdl.putString("type", "sms");
                bdl.putString("sms", address + ":" + body);
                Message msg = new Message();
                msg.setData(bdl);
                MainActivity.mMyHandle.sendMessage(msg);
            }
            if (!idCursor.isClosed()) {
                idCursor.close();
            }
        } else {
            // TODO: Nothing to do
        }
//        throw new UnsupportedOperationException("Not yet implemented");
    }
}